import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable, { ellipsisRender } from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Dialog, Message, Tab, NumberPicker } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useState, useEffect, useRef } from 'react';
import { column, ENUMS, toSelectDataSource } from './stores/definitions';
import { toJS } from 'mobx';
import BaseModal from './components/BaseModal';
import ArtificialDialog from './components/ArtificialDialog';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import moment from 'moment';

const tableId = uniqueId('tauTable-');

const Order = ({ queryParams }) => {
  const [modal, setModal] = useState({
    show: null,
    record: null,
  });
  const { orderStore: store, ruleStore } = useStore();
  const itemsRef = useRef(null);

  useEffect(() => {
    store.search = {
      groupIds: [ruleStore._group_id],
      ...queryParams,
    };
    const tempItems = toJS(store._tabItems);
    itemsRef.current = tempItems;

    if (queryParams) {
      updateStoreAndFilterItems();
    }

    return () => {
      store.skip = false;
      itemsRef.current = null;
    };

    function updateStoreAndFilterItems() {
      store.skip = true;
      store._orderStatus = '2';
      itemsRef.current = tempItems.filter(({ key }) => key !== '1' && key !== '0');
    }
  }, [ruleStore._group_id]);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { getOnDate, getOnPredict, orderStatus, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    const [predictFrom, predictTo] = getOnPredict || [];
    store.search = {
      from,
      to,
      predictFrom,
      predictTo,
      groupIds: [ruleStore._group_id],
      orderStatus: orderStatus && [orderStatus],
      ...queryParams,
      ...searchArgs,
    };
  };

  // 点击打开查看
  const handleOpenView = (result) => {
    setModal({ show: 'view', record: result });
  };

  // 点击打开查看
  const handleOnEdit = (result) => {
    setModal({ show: 'edit', record: result });
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal({ show: null, record: null });
  };

  const handleCancelOrder = (result) => {
    Dialog.confirm({
      content: t`确定要取消该订单吗？`,
      onOk: async () => {
        try {
          await store.cancelOrderIssue(result.id);
          Message.success({ content: t`取消成功` });
        } catch (error) {
          Message.error({ content: t`取消失败`, duration: 7000 });
          throw error;
        }
      },
    });
  };

  const handelOnUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const { count } = modal?.record;
        const { price, auxOrder } = toJS(result);
        if (count > 0) {
          Dialog.confirm({
            content: t`积分已手动修改，修改价格不会改变积分!`,
            onOk: async () => {
              try {
                await store.update({ ...toJS(result), originalPrice: price });
                Message.success({ content: t`更新成功` });
                handleCancel();
              } catch (error) {
                Message.error({ content: t`更新失败`, duration: 7000 });
                throw error;
              }
            },
          });
        } else {
          const utcTime = moment(auxOrder?.predictBeginDate).utc().format();
          _.set(result, 'auxOrder', {
            ...auxOrder,
            predictBeginDate: utcTime,
          });
          await store.update({ ...toJS(result), originalPrice: price });
          Message.success({ content: t`更新成功` });
          handleCancel();
        }
      } catch (error) {
        Message.error({ content: t`更新失败`, duration: 7000 });
        throw error;
      }
    }
  };

  const handleArtificial = (result) => {
    setModal({ show: 'artificial', record: result });
  };

  const artificialSubmit = async () => {
    try {
      const temp = modal?.record;
      const point = Number(modal?.record?.issueOrderPoint);
      temp.auxOrder.issueOrderPoint = point;
      temp.auxOrder.takeOrderPoint = -point;
      await store.update({ ...temp });
      Message.success({ content: t`修改成功` });
    } catch (error) {
      Message.error({ content: t`修改失败`, duration: 7000 });
      throw error;
    }
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        searchItems={[
          {
            name: 'getOnDate',
            type: 'date-range',
            props: {
              placeholder: [t`开始发单时间`, t`结束发单时间`],
            },
          },
          {
            name: 'getOnPredict',
            type: 'date-range',
            props: {
              placeholder: [t`预估开始时间`, t`预估结束时间`],
            },
          },
          {
            name: 'orderStatus',
            type: 'select',
            props: {
              placeholder: t`订单状态`,
              dataSource: toSelectDataSource(ENUMS.orderStatus),
            },
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Tab
          defaultActiveKey={'1'}
          activeKey={store.orderStatus}
          onChange={(v) => {
            store.orders = [];
            store.orderStatus = v;
          }}
        >
          {itemsRef?.current?.map((item) => (
            <Tab.Item key={item.key} title={item.label} />
          ))}
        </Tab>
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => {
            store.pg = pg;
          }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('orderNumber', {
              width: 160,
              cell: (v, i, r) => {
                return (
                  <Button
                    text
                    type="primary"
                    onClick={() => handleOpenView(r)}
                  >
                    {ellipsisRender(v)}
                  </Button>
                );
              },
            }),
            column('auxOrder.orderStatus', { width: 82 }),
            column('keepScore', {
              width: 66,
              cell: (v, i, r) => {
                const { issueOrderPoint } = r?.auxOrder;
                return (
                  <>
                    <Button text type="primary" onClick={() => handleArtificial(r)}>
                      {issueOrderPoint}
                    </Button>
                    {r?.auxOrder?.updatePointFlag ? (
                      <>
                        （<span>{t`手工`}</span>）
                      </>
                    ) : null}
                  </>
                );
              },
            }),
            column('price', { width: 88 }),
            column('itinerary', { width: 120 }),
            column('auxOrder.predictBeginDate', { width: 128, sortable: true }),
            column('auxOrder.publisherName', { width: 144 }),
            column('crDate', { width: 138, sortable: true }),
            column('auxOrder.auxTask.driverInfos.driverName', { width: 220 }),
            column('auxOrder.auxTask.driverInfos.takeOrderTime', { width: 128 }),
            {
              title: t`操作`,
              dataIndex: 'channelNumber',
              width: 120,
              cell: (_, __, r) => {
                const menu = [
                  {
                    title: t`编辑`,
                    onClick: () => handleOnEdit(r),
                  },
                  {
                    title: t`取消`,
                    onClick: () => handleCancelOrder(r),
                    color: 'red',
                  },
                ];
                return (
                  <MoreFuncDropDown dropdownItems={menu} maxShow={1} />
                );
              },
            },
          ]}
        />
      </div>
      <BaseModal modal={modal} setModal={setModal} onCancel={handleCancel} onSubmit={handelOnUpdate} />
      <ArtificialDialog modal={modal} onSubmit={artificialSubmit} setModal={setModal} onCancel={handleCancel} />
    </TauPage>
  );
};

export default observer(Order);
